import {defineStore} from 'pinia'
import router from '@/router/index.js'
import {reqUserLogout, userLogin} from "@/api/system/user.js";
import {getToken, removeToken, setToken} from "@/util/auth.js";
import {useLayoutStore} from "@/stores/layout/index.js";

export const useUserStore = defineStore('user', {
    state: () => {
        return {
            isLogin: false,
            loginUserInfo: {},
            roles: [],
            menus: []
        }
    },
    getters: {},
    actions: {
        async userLogin(loginForm) {
            try {
                const res = await userLogin(loginForm)
                if (res.code !== 200) {
                    return Promise.reject(res.msg)
                }
                this.isLogin = true
                this.loginUserInfo = res.data.user
                this.roles = res.data.roles
                this.menus = res.data.menus
                setToken(res.data.token)
                await router.push('/')
                return Promise.resolve(res)
            } catch (error) {
                console.log("进入")
                return Promise.reject(error)
            }
        },
        async logout() {
            if (getToken()){
                await reqUserLogout()
                removeToken()
                this.$reset()
                const layoutStore = useLayoutStore();
                layoutStore.$reset();
            }
            await router.push('/login')
        }
    },
    persist: {
        storage: sessionStorage,    //修改存储位置
        key: 'user-setting',   //设置存储的key,在这里是存在sessionStorage时的键
        pick: ['isLogin', 'loginUserInfo',"roles",'menus'],//指定要长久化的字段
    },
})

